"""
FileName：auth_manager.py
Description：
Author：gaojiahui
Time：2025/8/18 20:09
Website：https://gitee.com/gao-jiahui
"""
import base64
import time
import uuid

from config.settings import settings

from core.exceptions import AuthenticationError
from core.logger import logger
from utils.imageCode_util import ImageCode


class AuthManager:
    def __init__(self):
        from core.api_client import APIClient
        self.token = None
        self.token_expiry = 0
        self.api_client = APIClient()
        self.user_info = None
        self.captcha_mode = settings.CAPTCHA_MODE       # 从配置读取验证码模式
        self.fixed_captcha = settings.FIXED_CAPTCHA     # 从配置读取固定验证码
        self.get_image_code = ImageCode()

    def _get_basic_auth(self):
        """生成Basic认证头"""
        credentials = f"{settings.CLIENT_ID}:{settings.CLIENT_SECRET}"
        encoded_creds = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
        return f"Basic {encoded_creds}"

    def get_token(self, username=None, password=None, force_refresh=False):
        random_str = str(uuid.uuid4())
        # 获取图片验证码
        image_code = self.get_image_code.get_image_code(random_str = random_str)
        """获取或刷新JWT令牌"""
        username = username or settings.ADMIN_USER
        password = password or settings.ADMIN_PASSWORD

        # 检查令牌是否有效
        if self.token and time.time() < self.token_expiry and not force_refresh:
            return self.token

        logger.info(f"获取用户 {username} 的令牌")

        response = self.api_client.post(
            "/auth/oauth2/token",
            data = {
                "username": username,
                "password": password,
                "grant_type": "password",
                "randomStr": random_str,
                "scope": "server",
                # "code": image_code
                "code": settings.FIXED_CAPTCHA
            },
            headers = {
                "Authorization": self._get_basic_auth(),
                "Content-Type": "application/x-www-form-urlencoded"
            },
            skip_auth=True
        )

        if response.status_code != 200:
            raise AuthenticationError(f"认证失败: {response.text}")

        token_data = response.json()
        self.token = token_data['access_token']
        # 设置令牌过期时间（提前5分钟刷新）
        self.token_expiry = time.time() + float(token_data['expires_in']) - 300

        logger.info(f"令牌获取成功，有效期至: {time.ctime(self.token_expiry)}")
        return self.token

    def get_user_info(self):
        """获取当前用户信息"""
        if not self.token:
            self.get_token()

        response = self.api_client.get("/admin/user/info")
        if response.status_code == 200:
            self.user_info = response.json()['data']
            return self.user_info
        raise AuthenticationError("获取用户信息失败")

    def has_permission(self, permission):
        """检查用户是否有指定权限"""
        if not self.user_info:
            self.get_user_info()

        return permission in self.user_info['permission']

# 全局认证实例
auth_manager = AuthManager()